package task;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Pattern;

import org.eclipse.swt.graphics.ImageData;

import util.JdbcUtil;


public class ListAllShemasWithVersion extends DbTask {
	

	@Override
	public void run(Map<String, String> props) {
		ArrayList<String> schemas;
		String filter = props.get("filter");
		try {
			schemas = getSchemas(conn(), filter);
			String[] tab = new String[schemas.size()];
			int i=0;
			for (String schema : schemas) {
				String sql2 = String.format("select version from %s.DB_CURRENT_VERSION", schema);
				String version = JdbcUtil.getSingleString(conn(), sql2);
				tab[i++] = String.format("%11s : %s", version, schema);
			}
			Arrays.sort(tab);
			for (String s : tab) {
				System.out.println(s);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}

	public static ArrayList<String> getSchemas(Connection conn, String filter) throws SQLException {
		boolean oracle = conn.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle");
		ArrayList<String> schemas = new ArrayList<String>();
		Pattern pattern = null;

		if (filter != null && filter.trim().length()>0) {
			pattern = Pattern.compile(filter.toLowerCase());
		}
		if (oracle) {
			String sql = "select owner from all_tables where table_name='DB_CURRENT_VERSION'";
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String schema = rs.getString(1);
				if (pattern == null || pattern.matcher(schema.toLowerCase()).matches()) {
					schemas.add(schema);
				}
			}
			rs.close();
			stmt.close();

		} else {
			ResultSet rs = conn.getMetaData().getTables(null, null, "db_current_version", null);
			while (rs.next()) {
				String schema = rs.getString(2);
				if (pattern == null || pattern.matcher(schema.toLowerCase()).matches()) {
					schemas.add(schema);
				}
			}
		}
		return schemas;
	}

	@Override
	public String getDescription() {
		String desc = "List all NetMaster schemas with version\n (a regular expression filter may be provided)";
		return desc;
	}

	@Override
	public ImageData getImageData() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String[] propertyNames() {
		String[] props = { "filter" };
		return props;
	}
}
